package logic

import (
	"context"
	"encoding/json"
	"github.com/zeromicro/go-zero/core/logx"
	"goods/goodsrpc/goodsrpc"
	"goods/goodsrpc/internal/svc"
	"goods/models/cache"
	"goods/models/mysql"
	"time"
)

type GoodListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodListLogic {
	return &GoodListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GoodListLogic) GoodList(in *goodsrpc.GoodListRequest) (*goodsrpc.GoodListResponse, error) {
	// todo: add your logic here and delete this line
	var list []*goodsrpc.GoodList
	result, _ := cache.Rdb.Get(cache.Ctx, "goodList").Result()
	if result == "" {
		list = mysql.GoodsList(mysql.DB, list)
		marshal, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, "goodList", marshal, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &list)
	}
	return &goodsrpc.GoodListResponse{
		List: list,
	}, nil
}
